package com.wmh.baseservice.robot.controller;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wmh.baseservice.admin.service.AdRoleService;
import com.wmh.baseservice.common.mybatisplus.structure.LambdaQueryWrapperX;
import com.wmh.baseservice.common.utils.LogUtil;
import com.wmh.baseservice.common.utils.page.pojo.PageResult;
import com.wmh.baseservice.common.utils.page.util.PageUtil;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.common.utils.web.UserUtil;
import com.wmh.baseservice.robot.entity.RobotTaskTemplate;
import com.wmh.baseservice.robot.pojo.vo.tasktemplate.CopyTaskTemplateReqVO;
import com.wmh.baseservice.robot.pojo.vo.tasktemplate.TaskTemplatePageReqVO;
import com.wmh.baseservice.robot.service.RobotTaskTemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.List;
import java.util.Objects;

import static com.wmh.baseservice.common.utils.returnbody.ReturnBody.success;

/**
 * @author 谢骏
 * @date 2023/4/20 16:03
 **/
@Api(tags = "自动化机器-任务模板相关接口", value = "任务模板相关接口")
@RestController
@RequestMapping("robot/taskTemplate")
@Valid
public class RobotTaskTemplateController {

    @Resource
    private RobotTaskTemplateService robotTaskTemplateService;

    @Resource
    private AdRoleService adRoleService;

    @Resource
    private UserUtil userUtil;

    @ApiOperation("复制任务模板")
    @PostMapping("copy")
    @RequiresPermissions("robot.taskTemplate.addOrUpdate")
    public String copy(@Validated CopyTaskTemplateReqVO reqVO) {
        Long adId = userUtil.getId();
        robotTaskTemplateService.copyTaskTemplate(adId, reqVO);
        return success();
    }

    @ApiOperation("提交任务模板")
    @PostMapping("commit")
    @RequiresPermissions("robot.taskTemplate.addOrUpdate")
    public String commit(Long templateId,
                         @Size(min = 1, message = "请填写模板名称")
                         @NotBlank(message = "请填写模板名称")
                         String templateName,
                         @Size(min = 3, message = "请添加任务")
                         @NotBlank(message = "请添加任务")
                         String taskConfigSnapshot) {
        Long adId = userUtil.getId();
        LogUtil.info("commitTaskTemplate ==> adId: {} templateId: {}  templateName : {} taskConfigSnapshot : {}"
                , adId, templateId, templateName, taskConfigSnapshot);
        robotTaskTemplateService.commitTaskTemplate(adId, templateId, templateName, taskConfigSnapshot);
        return ReturnBody.success();
    }

    @ApiOperation("删除任务模板")
    @RequiresPermissions("robot.taskTemplate.delete")
    @PostMapping("delete")
    public String delete(
            @NotNull(message = "该数据丢失,请刷新重试或联系管理员")
            Long templateId
    ) {
        Long adId = userUtil.getId();
        LogUtil.info("deleteTaskTemplate => adId : {} templateId : {}", adId, templateId);
        if (!robotTaskTemplateService.removeById(templateId)) {
            return ReturnBody.error("系统异常,删除失败.请重试或联系管理员");
        }
        return ReturnBody.success();
    }

    @ApiOperation(value = "获取任务模板列表")
    @GetMapping("list")
    @RequiresPermissions("robot.taskTemplate.query")
    public String list(Boolean lookMe) {
        Long id = userUtil.getId();
        boolean hasSupperAdmin = adRoleService.isHasSupperAdmin(id);
        List<RobotTaskTemplate> list = robotTaskTemplateService.list(new LambdaQueryWrapperX<RobotTaskTemplate>()
                // 不是超级管理员 只能看自己的模板
                .eq(!hasSupperAdmin, RobotTaskTemplate::getAdId, id)
                // 是超级管理员 并且只看自己的数据
                .eq(hasSupperAdmin && lookMe != null && lookMe, RobotTaskTemplate::getAdId, id)
                .select(RobotTaskTemplate::getName,RobotTaskTemplate::getId,RobotTaskTemplate::getAdId)
        );
        return ReturnBody.success(list);
    }

    @ApiOperation(value = "获取任务模板分页")
    @PostMapping("page")
    @RequiresPermissions("robot.taskTemplate.query")
    public String page(@Validated TaskTemplatePageReqVO reqVO) {
        Long adId = userUtil.getId();
        boolean hasSupperAdmin = adRoleService.isHasSupperAdmin(adId);
        PageResult<RobotTaskTemplate> pageResult = new PageUtil<RobotTaskTemplate>(reqVO).startPage((page, wrapper) -> {
            LambdaQueryWrapper<RobotTaskTemplate> lambda = wrapper.lambda();
            // 是否只看自己 以及 名称模糊
            lambda.eq(reqVO.getLookMe(), RobotTaskTemplate::getAdId, adId)
                    .like(StrUtil.isNotBlank(reqVO.getName()), RobotTaskTemplate::getName, reqVO.getName());
            // 超级管理员可查看指定用户的模板
            lambda.eq(hasSupperAdmin && BooleanUtil.isFalse(reqVO.getLookMe()) && !Objects.isNull(reqVO.getAdId())
                    , RobotTaskTemplate::getAdId, reqVO.getAdId());
            robotTaskTemplateService.page(page, wrapper);
        });
        return success(pageResult);
    }
}
